﻿@{
    Layout = null;
}
@using CNKI.TPI.Web.Search.Model;
@using CNKI.TPI.Web.Base;
<script>
    function editDB(id, code, name, url, owner, password, searchtype,viewstr) {
        $("#DBID").val(id);
        $("#delfieldid").val("");
        $("#DBCode").val(code);
        $("#DBName").val(name);
        $("#DBUrl").val(url);
        $("#DBUser").val(owner);
        $("#DBPassword").val(password);
        $("#selectDB").val(searchtype);
        $("#DBObject").val(viewstr);
        //获取数据库字段
        $("#tableField tbody").html("");

        $.ajax({
            type: "GET",
            url: "@Html.Raw(Url.Action("GetDBFieldsList", "Admin_MultiDBPublish"))?dbcode=" + code,
            success: function (m) {
                if (m != null && m != "undefined") {
                    
                    for (var i = 0; i < m.length; i++) {

                        var checkcolumn = "<tr><td class=\"checkfields\"> <input type=\"checkbox\" class=\"f-checkbox\" value=" + m[i].SysID + " onclick=\"fieldsclick(this)\"></td>"
                               + "<td><input type=\"text\" value='" + m[i].Field + "' class=\"f-text span3\" maxlength=\"20\"> </td>"
                               + " <td><select class=\"f-select span3\">";
                        if (m[i].DataType == 1) {
                            checkcolumn += "<option value=\"1\" selected=\"selected\">string</option>";
                        }
                        else {
                            checkcolumn += "<option value=\"1\">string</option>";
                        }

                        if (m[i].DataType == 3) {
                            checkcolumn += "<option value=\"3\" selected=\"selected\">int</option>";
                        }
                        else {
                            checkcolumn += "<option value=\"3\">int</option>";
                        }

                        if (m[i].DataType == 4) {
                            checkcolumn += "<option value=\"4\" selected=\"selected\">datetime</option>";
                        }
                        else {
                            checkcolumn += "<option value=\"4\">datetime</option>";
                        }
                        checkcolumn += "</td></tr>"
                        $("#tableField tbody").append(checkcolumn);
                    }
                }
            },
            error: function (e)
            { }
        })
        $(".talkDivBg").show();
        $(".dbinfo").show();
    }
    function delDB() {
        var ckbs = $(".checkboxdb input[type='checkbox']:checked");
        if (ckbs.size() == 0) {
            messageAlert("请选择要删除的记录！");
            return;
        }
        var checkedstr = [];
        ckbs.each(function () {
            checkedstr.push($(this).val());
        })
        delfunc(checkedstr.toString());
    }
    function delfunc(idstr) {
        confirmDialog('确定要删除吗?', function () {
            $.ajax({
                type: "GET",
                url: "@Html.Raw(Url.Action("DelDbAndFields", "Admin_MultiDBPublish"))?dbid=" + idstr,
                success: function (m) {
                    if (m == "True") {
                        //刷新
                        $('#pageIndexNow').val(1);
                        SearchData();
                    }
                    else {
                        messageAlert("操作失败！");
                    }
                },
                error: function (e)
                { }
            })
        });
    }
    function addDB() {
        $("#DBID").val(0);
        $("#tableField tbody").html("");
        $("#delfieldid").val("");
        $("#DBCode").val("");
        $("#DBName").val("");
        $("#DBUrl").val("");
        $("#DBUser").val("");
        $("#DBPassword").val("");
        $("#DBObject").val("");
        $(".talkDivBg").show();
        $(".dbinfo").show();
    }
    function closeDB() {
        $(".talkDivBg").hide();
        $(".dbinfo").hide();
    }
    function validText() {
        //验证
        var dbname = $("#DBName").val();
        var dbcode = $("#DBCode").val();
        var dburl = $("#DBUrl").val();
        var viewobject = $("#DBObject").val();
        var userbject = $("#DBUser").val();
        if (dbname != "") {
            if (!regtext(dbname)) {
                messageAlert("数据库名称不允许录入特殊字符！");
                return false;
            }
        }
        else {
            messageAlert("数据库名称不允许为空！");
            return false;
        }
        if (dbcode != "") {
            if (!regtext(dbcode)) {
                messageAlert("数据库编码不允许录入特殊字符！");
                return false;
            }
        }
        else {
            messageAlert("数据库编码不允许为空！");
            return false;
        }
        if (dburl == "") {
            messageAlert("接口路径不允许为空！");
            return false;
        }
        if (viewobject != "") {
            if (!regtext(viewobject)) {
                messageAlert("对象不允许录入特殊字符！");
                return false;
            }
        }
        if (userbject != "") {
            if (!regtext(userbject)) {
                messageAlert("用户名不允许录入特殊字符！");
                return false;
            }
        }
        
        var m = 0;
        $("#tableField tr td:nth-child(2)").each(function () {
            var str = $(this).find("input").val();
            if (!regtext(str)) {
                m = 1;
            }
        });
        if (m == 1) {
            messageAlert("字段名不允许录入特殊字符！");
            return false;
        }


        return true;

    }
    function saveDB() {
        if (validText()) {
            //验证是否存在
            
            var saveurl = "@Html.Raw(Url.Action("IsExistsDB", "Admin_MultiDBPublish"))";
            var savedata = { "name": $("#DBName").val(), "code": $("#DBCode").val(), "id": $("#DBID").val() };
            $.ajax({
                type: "POST",
                url: saveurl,
                data: JSON.stringify(savedata),
                contentType: "application/json",
                success: function (m) {
                    if (m == 1) {
                        messageAlert("数据库名称重复，请重新录入！");
                        return false;
                    }
                    else if (m == 2) {
                        messageAlert("数据库编码重复，请重新录入！");
                        return false;
                    }
                    else if (m == 0) {
                        dealinfo(); //保存
                    }
                },
                error: function (e) {
                    messageAlert("数据库重复验证失败，请刷新重试！");
                    return false;
                }
            })

        }
    }
    function dealinfo() {
        //保存
        var date = new Date();
        var dbobjdata = {
            "SysID": $("#DBID").val(), "DatabaseName": $("#DBName").val(), "DatabaseCode": $("#DBCode").val(), "VIP": $("#DBUrl").val(), "VViewName": $("#DBObject").val(),
            "VUserName": $("#DBUser").val(), "VPassWord": $("#DBPassword").val(), "SearchType": $("#selectDB").val(), "VisibleFlag": 1, "CreateDate": date.toLocaleDateString()
        };
        var list = [];
        
        $('#tableField tbody tr').each(function () {
            var str = $(this).children().eq(1).find("input").val();
            if (str != "") {
                var strfields = {
                    "DatabaseCode": $("#DBCode").val(),
                    "SysID": $(this).children().eq(0).find("input").val(),
                    "Field": $(this).children().eq(1).find("input").val(),
                    "DataType": $(this).children().eq(2).find("select").val()
                }
                list.push(strfields);
            }
        })

        var saveurl = "@Html.Raw(Url.Action("DealDataBaseInfo", "Admin_MultiDBPublish"))";
        var savedata = { "dbobj": dbobjdata, "list": list, "fieldstr": $("#delfieldid").val() };
        $.ajax({
            type: "POST",
            url: saveurl,
            data: JSON.stringify(savedata),
            contentType: "application/json",
            success: function (m) {
                if (m == "True") {
                    closeDB();
                    $('#pageIndexNow').val(1);
                    SearchData();
                }
                else {
                    messageAlert("操作失败！");
                }
            },
            error: function (e)
            { }
        })
    }
    //添加字段
    function addFields() {
        var checkcolumn = "<tr><td class=\"checkfields\"> <input type=\"checkbox\" value=\"0\" class=\"f-checkbox\" onclick=\"fieldsclick(this)\"></td>"
       + "<td><input type=\"text\" class=\"f-text span3\" maxlength=\"20\"> </td>"
       + " <td><select class=\"f-select span3\"><option value=\"1\">string</option><option value=\"3\">int</option><option value=\"4\">datetime</option></select></td></tr>"
        $("#tableField tbody").append(checkcolumn);

    }
    //删除字段
    function delFields() {
        var ckbs = $(".checkfields input[type='checkbox']:checked");
        if (ckbs.size() == 0) {
            messageAlert("请选择要删除的记录！");
            return;
        }
        confirmDialog('确定要删除吗?', function () {
            ckbs.each(function () {
                //遍历删除
                
                var fieldsid = $(this).parent().parent().children().eq(0).find("input").val();
                if (fieldsid != 0)
                {
                    var str = $("#delfieldid").val();
                    $("#delfieldid").val(str + "," + fieldsid);
                }
                $(this).parent().parent().remove();
            })
            $(".checkallfields").removeAttr("checked", "checked");
        })


    }
    ///全选
    function checkall(e) {
        if ($(e).attr("checked") == "checked") {
            $(".checkfields input[type='checkbox']").each(function () {
                $(this).attr("checked", "checked");
            })
        }
        else {
            $(".checkfields input[type='checkbox']").each(function () {
                $(this).removeAttr("checked", "checked");
            })
        }
    }

    function fieldsclick(e) {
        //循环判断列表中的checkbox，如果全部选中则全选框呈勾选状态
        if ($(e).attr("checked") != "checked") {
            $(".checkallfields").removeAttr("checked", "checked");
        }
        else {
            dealchecked(".checkfields input[type='checkbox']", ".checkallfields");
        }
    }
    function DBlistcheckall(e) {
        if ($(e).attr("checked") == "checked") {
            $(".checkboxdb input[type='checkbox']").each(function () {
                $(this).attr("checked", "checked");
            })
        }
        else {
            $(".checkboxdb input[type='checkbox']").each(function () {
                $(this).removeAttr("checked", "checked");
            })
        }
    }
    function dbclick(e) {
        //循环判断列表中的checkbox，如果全部选中则全选框呈勾选状态
        if ($(e).attr("checked") != "checked") {
            $(".dblistall").removeAttr("checked", "checked");
        }
        else {
            dealchecked(".checkboxdb input[type='checkbox']", ".dblistall");
        }

    }

    function dealchecked(checkedsub, checkedparent) {
        var m = 0;
        $(checkedsub).each(function () {
            if ($(this).attr("checked") != "checked") {  //遍历判断是否存在没有选中的记录
                m = 1;
            }
        })
        if (m == 1) {
            $(checkedparent).removeAttr("checked", "checked");
        }
        else {
            $(checkedparent).attr("checked", "checked");
        }
    }
</script>
<div class="wrapR-c">
    <input type="hidden" id="DBID" value="0" />
    <input type="hidden" id="delfieldid" value="" />
    <table width="100%" cellspacing="0" cellpadding="0" border="0" class="table table-grey">
        <thead>
            <tr class="thead">
                <th class="tdnum">
                    <input type="checkbox" class="dblistall" value="" name="" onclick="DBlistcheckall(this)">序号</th>
                <th class=''>数据库名称</th>
                <th class='tl'>数据库编码</th>
                <th>创建时间</th>
                <th>接口路径</th>
                <th>操作</th>
            </tr>
        </thead>
        <tbody>
            @{if (ViewBag.DbList != null)
              {
                  int sortno = ViewBag.PageSize * (ViewBag.PageNow - 1) + 1;
                  foreach (SYS_CMS_DATABASE item in ViewBag.DbList)
                  {

                      string str = "even";
                      if (sortno % 2 == 0)
                      {
                          str = "odd";
                      }
                <tr class='@str'>
                    <td class="checkboxdb">
                        <input type="checkbox" value="@item.SysID" onclick="dbclick(this)" >@sortno</td>
                    <td>@Html.Raw(StringHelper.ConvertHighlightFlag(item.DatabaseName))</td>
                    <td>@item.DatabaseCode</td>
                    <td class="tc">@if (item.CreateDate != null)
                                   {@item.CreateDate.ToString("yyyy-MM-dd")}</td>
                    <td>@item.DatabaseURL</td>

                    <td class="tc">

                        <a onclick="editDB('@item.SysID','@item.DatabaseCode','@item.DatabaseName','@item.VIP','@item.VUserName','@item.VPassWord','@item.SearchType','@item.VViewName')" href="javascript:void(0)">编辑</a>
                        <a onclick="delfunc('@item.SysID')" href="javascript:void(0)">删除</a>
                    </td>
                </tr>sortno = sortno + 1;
                  }
              }

            }
        </tbody>
    </table>

    @*//分页*@
    <div class="pagenav pagenav-02">
        @*上一页*@
        @if (ViewBag.TotalPage > 0)
        {
            if (ViewBag.PageNow != 1)
            {
                int thispage = ViewBag.PageNow - 1;
            <a href="javascript:void(0);" class="page-prev" onclick="searchPageNew('@thispage')" >上一页</a>
            }
            else
            {
            <a href="javascript:return false;"  onclick="return false" class="page-prev disable">上一页</a>
            }
@*循环初始化页码*@
            foreach (string numpage in ViewBag.PageList)
            {
                if (numpage != "0")
                {
                    int m = int.Parse(numpage);
                    if (m == ViewBag.PageNow)
                    {
            <a href="javascript:void(0);" class="active" onclick="searchPageNew('@numpage')">@numpage</a>
                    
                    }
                    else
                    {
            <a href="javascript:void(0);" onclick="searchPageNew('@numpage')">@numpage</a>
                    }

                }
                else
                {
                    <i class="iconfont icon-dian2"></i>
                }

            }
@*下一页*@
            if (ViewBag.TotalPage > 0 && ViewBag.PageNow != ViewBag.TotalPage)
            {
                int nextpage = ViewBag.PageNow + 1;
            <a href="javascript:void(0);" class="page-next" onclick="searchPageNew('@nextpage')" >下一页</a>
            }
            else
            {
            <a href="javascript:return false;"  onclick="return false" class="page-prev disable">下一页</a>
            }
        }
        @if (ViewBag.DbList == null || ViewBag.DbList.Count == 0)
        {
            <label>暂无数据！</label>
        
        }
        else
        {
          
            <label>共 </label>
            <label>@ViewBag.Count </label>
            <label>条数据 </label>
        }
    </div>
</div>
<div class='posr'>
    <a class="btn btn-m btn-submit btn-defa-f" href="javascript:void(0);" onclick="addDB()">添加</a>
    <a class="btn btn-m btn-submit btn-defa-f" href="javascript:void(0);" onclick="delDB()">删除</a>
</div>

<!--透明背景-->
<div class="talkDivBg" style="display: none; z-index: 999">

    <!--talkDiv弹出层(不带图片，宽550)-->
    <div class="talkDiv talkW-550 form-h form-h-8em dbinfo" style='margin-top: -278px; display: none'>
        <div class="talkDiv-title">
            <span>添加外部资源</span>
            <a class="icon icon-close" title="关闭" onclick="closeDB()" href="javascript:void(0);"><i class="iconfont icon-error3"></i></a>
        </div>
        <div class="talkDiv-body talkDiv-body1 ">
            <h3 class='box-h box-h-noborder'>
                数据库基本信息
            </h3>
            <div class="f-gp">
                <div class="f-lb">
                    <label class="f-label">数据库名称：</label>
                </div>
                <div class="f-ct">
                    <input type="text" value="" class="f-text span4" id="DBName" maxlength="255">
                    <span class="f-label-re">*</span>
                </div>
            </div>

            <div class="f-gp">
                <div class="f-lb">
                    <label class="f-label">数据库编码：</label>
                </div>
                <div class="f-ct">
                    <input type="text" value="" class="f-text span4" id="DBCode" maxlength="255">
                    <span class="f-label-re">*</span>
                </div>
            </div>
            <div class="f-gp">
                <div class="f-lb">
                    <label class="f-label">对象：</label>
                </div>
                <div class="f-ct">
                    <input type="text" value="" class="f-text span4" id="DBObject" maxlength="255">
                </div>
            </div>

            <div class="f-gp">
                <div class="f-lb">
                    <label class="f-label">接口路径：</label>
                </div>
                <div class="f-ct">
                    <input type="text" value="" class="f-text span4" id="DBUrl" maxlength="32767">
                    <span class="f-label-re">*</span>
                </div>
            </div>

            <div class="f-gp">
                <div class="f-lb">
                    <label class="f-label">数据库类型：</label>
                </div>
                <div class="f-ct">

                    <select class="f-select span3" id="selectDB">
                        @{
                        IDictionary<string, int> selist = ConfigHelper.GetExtDataSourceList();
                        foreach (KeyValuePair<string, int> kvp in selist)
                        {
                                <option value="@kvp.Value">@kvp.Key</option>
                        }

                        }
                    </select>
                </div>
            </div>
            <div class="f-gp">
                <div class="f-lb">
                    <label class="f-label">用户名：</label>
                </div>
                <div class="f-ct">
                    <input type="text" value="" class="f-text span4" id="DBUser" maxlength="255">
                </div>
            </div>
            <div class="f-gp">
                <div class="f-lb">
                    <label class="f-label">密码：</label>
                </div>
                <div class="f-ct">
                    <input type="text" value="" class="f-text span4" id="DBPassword" maxlength="20">
                </div>
            </div>
            <div class="box">
                <h3 class='box-h box-h-noborder'>
                    数据库字段设置
                </h3>
                <div class="btn-group clearfix inline-block ml10" style="padding-top: 10px; padding-bottom: 10px">
                    <a class="btn btn-white fl" href="javascript:void(0);" onclick="addFields()">添加</a>
                    <a class="btn btn-white" style="margin-left: 10px" href="javascript:void(0);" onclick="delFields()">删除</a>


                </div>
                <table id="tableField" width="100%" class="table table-wr">
                    <thead>
                        <tr class="thead">
                            <th class="tdnum tdnum1">
                                <input class="checkallfields" type="checkbox" onclick="checkall(this)">
                            </th>
                            <th>字段名</th>
                            <th>类型</th>
                        </tr>
                    </thead>
                    <tbody></tbody>
                </table>

            </div>

            <div class="f-gp">
                <div class="f-lb">
                    <label class="f-label"></label>
                </div>
                <div class="f-ct" style="margin-left: 150px; margin-top: 50px">
                    <a href="javascript:void(0);" class="btn btn-m btn-prim-f btn-submit" onclick="saveDB()">保存</a>
                    &#12288;<a href="javascript:void(0);" class="btn btn-m btn-submit btn-defa-f" onclick="closeDB()">取消</a>
                </div>
            </div>

        </div>
    </div>
</div>
